<template>
  <div>
    <Header></Header>
    <div class="mybody clearfix">
      <div class="left">
        <quill-editor
          class="ql-editor"
          v-model="content"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)"
          @focus="onEditorFocus($event)"
          @change="onEditorChange($event)"
        >
        </quill-editor>
      </div>
      <div class="right">
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <!-- 选择当前文章的模块，不同模块后续的表单内容都不同 -->
          <el-form-item label="文章模块" prop="module">
            <el-select
              v-model="ruleForm.module"
              placeholder="文章模块"
              @change="changeModule"
            >
              <el-option label="话题广场" value="话题广场"></el-option>
              <!-- 只有教师才能选择教师资源分享 -->
              <el-option
                v-show="identity == 1"
                label="教师资源分享"
                value="教师资源分享"
              ></el-option>
              <el-option label="新生可了解" value="新生可了解"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <!-- 根据上述选择的模块不同，下面的topic也将对应不同的三种格式 -->
          <!-- 只有选择了话题广场才能选择对应的话题标签 -->
          <el-form-item
            label="文章话题"
            prop="topic"
            v-if="ruleForm.module == '话题广场'"
          >
            <el-input v-model="ruleForm.topic"></el-input>
            <el-popover
              placement="left"
              width="500"
              height="600"
              v-model="visible"
            >
              <div
                class="fl topicItem"
                v-for="tag in tags"
                :key="tag.tagname"
                @click="addThisTopic(tag.tagname)"
              >
                {{ tag.tagname }}
              </div>
              <el-button slot="reference" class="addinterest"
                >选择话题</el-button
              >
            </el-popover>
            <el-button type="primary" @click="clearTopic">清空话题</el-button>
          </el-form-item>
          <!-- 当选择的是教师资源分享时，话题标签变为所属科目 -->
          <el-form-item
            v-if="ruleForm.module == '教师资源分享'"
            label="所属科目"
            prop="topic"
          >
            <el-select v-model="ruleForm.topic" placeholder="所属科目">
              <el-option
                v-for="tag in tags"
                :key="tag.tagname"
                :label="tag.tagname"
                :value="tag.tagname"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 当选择的是新生可了解时，话题标签变为所属栏目 -->
          <el-form-item
            v-if="ruleForm.module == '新生可了解'"
            label="所属栏目"
            prop="topic"
          >
            <el-select v-model="ruleForm.topic" placeholder="所属栏目">
              <!-- 只有管理员才能发布通知 -->
              <el-option
                v-if="isAdmin"
                label="最新通知"
                value="最新通知"
              ></el-option>
              <el-option label="入学指南" value="入学指南"></el-option>
              <el-option label="日常生活" value="日常生活"></el-option>
              <el-option label="学业疑难" value="学业疑难"></el-option>
            </el-select>
          </el-form-item>
          <!-- 只有选择了话题广场同时是教师才能发布提问帖 -->
          <el-form-item
            v-show="identity == 1 && ruleForm.module == '话题广场'"
            label="提问帖"
            prop="ifask"
          >
            <el-radio-group v-model="ruleForm.ifask">
              <el-radio label="是"></el-radio>
              <el-radio label="否"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="答案"
            prop="answer"
            v-show="ruleForm.ifask == '是'"
          >
            <el-input type="textarea" v-model="ruleForm.answer"></el-input>
          </el-form-item>
          <el-form-item
            label="截止日期"
            required
            v-show="ruleForm.ifask == '是'"
          >
            <el-col :span="11">
              <el-form-item prop="date1">
                <el-date-picker
                  type="date"
                  placeholder="选择日期"
                  v-model="ruleForm.date1"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col class="line" :span="2"></el-col>
            <el-col :span="11">
              <el-form-item prop="date2">
                <el-time-picker
                  placeholder="选择时间"
                  v-model="ruleForm.date2"
                  style="width: 100%"
                ></el-time-picker>
              </el-form-item>
            </el-col>
          </el-form-item>
          <el-form-item>
            <el-button
              v-show="ruleForm.ifask == '是'"
              @click="ruleForm.ifask = '否'"
              >取消</el-button
            >
          </el-form-item>
          <el-form-item label="摘要" prop="abstract">
            <el-input type="textarea" v-model="ruleForm.abstract"></el-input>
          </el-form-item>
          <el-form-item label="附件" prop="appendix">
            <el-upload
              ref="upload"
              class="upload-demo"
              :action="uploadUrl"
              :before-remove="beforeRemove"
              multiple
              :file-list="fileList"
              :on-success="onUploadSuccess"
              :auto-upload="false"
              :on-change="handleFileChange"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                您可以上传的资料包括Png、Jpeg、Word、Pdf等各种格式！
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addArticle">发布</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import forumApi from "@/api/forumApi";
import personApi from "@/api/personApi";
import { quillEditor } from "vue-quill-editor";

import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import * as Quill from "quill"; // 引入编辑器

// 调整上传图片大小
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageResize", ImageResize);

import tagApi from "@/api/tagApi";

export default {
  name: "post",
  mounted() {
    //下面部分代码都是为了实现富文本编辑器的正常使用
    // 自定义字体大小
    const Size = Quill.import("attributors/style/size");
    Size.whitelist = ["10px", "12px", "16px", "18px", "20px", "30px", "32px"];
    Quill.register(Size, true);
    // 自定义字体类型
    var fonts = [
      "SimSun",
      "SimHei",
      "Microsoft-YaHei",
      "KaiTi",
      "FangSong",
      "Arial",
      "sans-serif",
    ];
    var Font = Quill.import("formats/font");
    Font.whitelist = fonts;
    Quill.register(Font, true);

    //富文本编辑器选项提示
    // toolbar标题
    const titleConfig = [
      { Choice: ".ql-insertMetric", title: "跳转配置" },
      { Choice: ".ql-bold", title: "加粗" },
      { Choice: ".ql-italic", title: "斜体" },
      { Choice: ".ql-underline", title: "下划线" },
      { Choice: ".ql-header", title: "段落格式" },
      { Choice: ".ql-strike", title: "删除线" },
      { Choice: ".ql-blockquote", title: "块引用" },
      { Choice: ".ql-code", title: "插入代码" },
      { Choice: ".ql-code-block", title: "插入代码段" },
      { Choice: ".ql-font", title: "字体" },
      { Choice: ".ql-size", title: "字体大小" },
      { Choice: '.ql-list[value="ordered"]', title: "编号列表" },
      { Choice: '.ql-list[value="bullet"]', title: "项目列表" },
      { Choice: ".ql-direction", title: "文本方向" },
      { Choice: '.ql-header[value="1"]', title: "h1" },
      { Choice: '.ql-header[value="2"]', title: "h2" },
      { Choice: ".ql-align", title: "对齐方式" },
      { Choice: ".ql-color", title: "字体颜色" },
      { Choice: ".ql-background", title: "背景颜色" },
      { Choice: ".ql-image", title: "图像" },
      { Choice: ".ql-video", title: "视频" },
      { Choice: ".ql-link", title: "添加链接" },
      { Choice: ".ql-formula", title: "插入公式" },
      { Choice: ".ql-clean", title: "清除字体格式" },
      { Choice: '.ql-script[value="sub"]', title: "下标" },
      { Choice: '.ql-script[value="super"]', title: "上标" },
      { Choice: '.ql-indent[value="-1"]', title: "向左缩进" },
      { Choice: '.ql-indent[value="+1"]', title: "向右缩进" },
      { Choice: ".ql-header .ql-picker-label", title: "标题大小" },
      { Choice: '.ql-header .ql-picker-item[data-value="1"]', title: "标题一" },
      { Choice: '.ql-header .ql-picker-item[data-value="2"]', title: "标题二" },
      { Choice: '.ql-header .ql-picker-item[data-value="3"]', title: "标题三" },
      { Choice: '.ql-header .ql-picker-item[data-value="4"]', title: "标题四" },
      { Choice: '.ql-header .ql-picker-item[data-value="5"]', title: "标题五" },
      { Choice: '.ql-header .ql-picker-item[data-value="6"]', title: "标题六" },
      { Choice: ".ql-header .ql-picker-item:last-child", title: "标准" },
      { Choice: '.ql-size .ql-picker-item[data-value="small"]', title: "小号" },
      { Choice: '.ql-size .ql-picker-item[data-value="large"]', title: "大号" },
      {
        Choice: '.ql-size .ql-picker-item[data-value="huge"]',
        title: "超大号",
      },
      { Choice: ".ql-size .ql-picker-item:nth-child(2)", title: "标准" },
      { Choice: ".ql-align .ql-picker-item:first-child", title: "居左对齐" },
      {
        Choice: '.ql-align .ql-picker-item[data-value="center"]',
        title: "居中对齐",
      },
      {
        Choice: '.ql-align .ql-picker-item[data-value="right"]',
        title: "居右对齐",
      },
      {
        Choice: '.ql-align .ql-picker-item[data-value="justify"]',
        title: "两端对齐",
      },
    ];
    for (let item of titleConfig) {
      let tip = document.querySelector(".quill-editor " + item.Choice);
      if (!tip) continue;
      tip.setAttribute("title", item.title);
    }
  },
  created() {
    this.getPersonInfo();
  },
  components: {
    quillEditor,
  },
  data() {
    return {
      //富文本编辑器收集的内容
      content: `<p>请在这里输入你的内容~</p>`, //双向数据绑定数据,
      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线
            ["blockquote", "code-block"], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表
            [{ script: "sub" }, { script: "super" }], // 上标/下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向
            [
              {
                size: [
                  "12",
                  "14",
                  "16",
                  "18",
                  "20",
                  "22",
                  "24",
                  "28",
                  "32",
                  "36",
                ],
              },
            ], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ["clean"], // 清除文本格式
            ["image", "video"], // 链接、图片、视频
          ],
          // 调整图片大小
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        },
        placeholder: "请输入正文",
      },
      userInfo: "",
      //用于控制话题选项是否可见
      visible: false,
      //右侧表单数据
      ruleForm: {
        userIdentity: "教师",
        module: "",
        title: "",
        topic: "",
        ifask: "否",
        abstract: "",
        question: "",
        answer: "",
        // 下面的是问题贴截至时间
        date1: "",
        date2: "",
        appendix: "",
      },
      tags: [],
      attachmentUrls: [],
      uploadUrl: "http://localhost:8081/file/addFile",
      //上传的附件列表
      fileList: [],
      //这个参数用于确认文件是否合法，将不会传给后端
      ifLegal: true,
      //右侧表单规则
      rules: {
        module: [
          {
            required: true,
            message: "请选择发布文章的模块",
            trigger: "blur",
          },
        ],
        title: [
          { required: true, message: "请输入文章标题", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        topic: [
          { required: true, message: "请选择至少一个话题", trigger: "blur" },
        ],
        ifask: [
          { required: true, message: "请选择是否为问题贴", trigger: "change" },
        ],
        abstract: [{ required: true, message: "请输入摘要", trigger: "blur" }],
      },
      identity: 1,
      isAdmin: false,
    };
  },
  methods: {
    //onEditor开头的均为富文本编辑器的操作
    // 失去焦点事件
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    // 获得焦点事件
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    // 准备富文本编辑器
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    // 内容改变事件
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },
    //右侧表单操作
    submitForm(formName) {
      //如果是问题贴，那么要求必须发在话题广场模块
      if (this.ruleForm.ifask == "是" && this.ruleForm.module != "话题广场") {
        alert("问题贴只能在话题广场发布");
        return;
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          alert("submit!");
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //添加话题操作如下
    addThisTopic(newTopic) {
      if (this.ruleForm.topic.length == 0) {
        this.ruleForm.topic = newTopic;
      } else {
        this.ruleForm.topic = this.ruleForm.topic + "," + newTopic;
      }
    },
    clearTopic() {
      this.ruleForm.topic = "";
    },

    beforeRemove(file, fileList) {
      //只有在上传成功后才会有移出操作，如果上传文件不合法，那么就需要移除操作
      if (this.ifLegal == true) {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    },
    //触发submit函数后将fileList中的文件逐个上传并逐个触发该函数，作用是更新fileList为成功上传后的文件列表同时将后端返回的URL封装
    onUploadSuccess(attachmentUrl, file, fileList) {
      this.fileList = fileList;
      this.attachmentUrls.push(attachmentUrl);
    },
    changeModule(moduleName) {
      if (moduleName == "话题广场") {
        this.tags = [
          {
            tagname: "前端",
          },
          {
            tagname: "后端",
          },
          {
            tagname: "情感",
          },
          {
            tagname: "日常",
          },
        ];
      } else if (moduleName == "教师资源分享") {
        this.tags = [
          {
            tagname: "操作系统",
          },
          {
            tagname: "计算机图形学",
          },
          {
            tagname: "数据库组成原理",
          },
          {
            tagname: "数据可视化",
          },
        ];
      } else if (moduleName == "新生可了解") {
      }
    },
    //将附件的URL和当前帖子的其他参数打包发给后端进行存储
    addArticle() {
      this.$refs.upload.submit();
      //通过计时器来确保上述文件上传完毕后已经获取到所有URL才正式发帖
      var timer = setTimeout(() => {
        var article = this.packageArticle(this.ruleForm);
        console.log(article);
        forumApi.addArticle(article).then((response) => {
          if (response.code == "200") {
            this.$message({
              message: "文章发表成功",
              type: "success",
            });
          }
        });
      }, 1000);
    },
    //根据Form表单中填写的数据封装article
    packageArticle(form) {
      let article = {};
      article.attachmentUrls = "";
      for (var i = 0; i < this.attachmentUrls.length; i++) {
        article.attachmentUrls += this.attachmentUrls[i];
        if (i != this.attachmentUrls.length - 1) {
          article.attachmentUrls += ",";
        }
      }
      // article.attachmentUrls = this.attachmentUrls;
      console.log(this.attachmentUrls);
      console.log(form.module);
      if (form.module == "话题广场") article.pBoardId = 0;
      else if (form.module == "教师资源分享") article.pBoardId = 1;
      else if (form.module == "新生可了解") article.pBoardId = 2;
      article.title = form.title;
      article.content = this.content;
      article.summary = form.abstract;
      article.tag = form.topic;
      if (form.ifask == "否") article.questionType = 0;
      else if (form.ifask == "是") {
        article.questionType = 1;
        article.deadLine = this.packageDeadLine();
      }
      alert(this.attachmentUrls.length);
      console.log(this.attachmentUrls);
      article.answer = form.answer;
      if (this.attachmentUrls.length == 0) article.attachmentType = 0;
      else if (this.attachmentUrls.length > 0) {
        article.attachmentType = 1;
      }
      return article;
    },
    packageDeadLine() {
      var date = this.ruleForm.date1;
      var time = this.ruleForm.date2;
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      var hh = time.getHours();
      var mm = time.getMinutes();
      var ss = time.getSeconds();
      var deadLine =
        year + "-" + month + "-" + strDate + " " + hh + ":" + mm + ":" + ss;
      return deadLine;
    },
    //控制临时文件上传时的fileList与暂存的文件保持一致
    handleFileChange(file, fileList) {
      this.fileList = fileList;
    },
    findAllTag() {
      tagApi.findAllTag().then((response) => {
        this.tags = response.data;
      });
    },
    getPersonInfo() {
      personApi.getPersonInfo().then((response) => {
        var userInfo = response.data[0];
        this.identity = userInfo.identity;
        this.isAdmin = userInfo.isadmin;
      });
    },
  },
};
</script>

<style lang="css" scoped>
.mybody {
  margin: 0 auto;
  width: 90%;
}
.left {
  float: left;
  width: 60%;
  /* height: 600px; */
  border-radius: 5px;
  margin-right: 20px;
  background-color: white;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
}
.right {
  float: left;
  overflow-y: auto;
  width: 35%;
  height: 600px;
  border-radius: 5px;
  padding-right: 10px;
  padding-top: 10px;
  background-color: white;
  box-shadow: 0 0 3px rgba(0, 0, 0, 0.1);
}
::v-deep .ql-editor {
  min-height: 500px;
  /* max-height: 500px; */
  /* height: 500px; */
}
.addinterest {
  margin-top: 10px;
  margin-right: 20px;
}
.topicItem {
  height: 40px;
  line-height: 40px;
  padding: 0 20px;
  border: 1px solid rgba(0, 0, 0, 0.2);
  border-radius: 20px;
  margin: 10px 0;
  margin-right: 10px;
}
.topicItem:hover {
  cursor: pointer;
  color: #409eff;
  background-color: #ecf5ff;
  border: #a0cfff;
}
</style>
